/**
 * 修改/新增用户页面js
 * Created by zhangsi on 2015/10/13.
 */
var userAdd = new XFApp.client();
XFApp.client.prototype.add = {
    isSubmitting : false,
    successCode : 10000,
    deptList : {},
    urlItems : {
        saveURL : basePath +"/user/saveOrUpdate",
        roleListUrl : basePath + "/role/ajax/list",
        deptListUrl : basePath + "/dept/ajax/list",
        userListUrl : basePath + "/user"
    },
    saveOrUpdate : function(){
        var _this = this;
        //获取选中的角色
        var roleIds = "";
        $("#roles_div input:checked").each(function(){
            var _input = $(this);
            var roleId = _input.attr('data-id');
            roleIds += roleId + ",";
        });
        roleIds = roleIds.length > 1 ? roleIds.substr(0,roleIds.length-1) : roleIds;
        $("#roleIds").val(roleIds);
        $.ajax( {
            url:this.urlItems.saveURL,
            data:$('#editForm').serialize(),
            type:'post',
            cache:false,
            dataType:'json',
            success:function(data) {
                if(data.code == _this.successCode){
                    webDialogUtil.callbackConfrimAlert(data.msg, function(){window.location = userAdd.add.urlItems.userListUrl});
                }else{
                    webDialogUtil.simple(data.msg);
                }
            },
            error : function() {
                webDialogUtil.simpleAlert("操作失败!");
            }
        });
    },
    formValidate : function(){
        $('#editForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                username: {
                    group: '.col-lg-4',
                    validators: {
                        notEmpty: {message: '登陆用户名不能为空'}
                    }
                },
                realName: {
                    group: '.col-lg-4',
                    validators: {
                        notEmpty: {message: '真实姓名不能为空'}
                    }
                },
                password: {
                    group: '.col-lg-4',
                    validators: {
                        notEmpty: {message: '密码不能为空'},
                        stringLength : {
                            min : 6,
                            max : 20,
                            message : '密码长度为6-20个字符'
                        }
                    }
                },
            }
        });
    },
    initRoleList : function(){
        var roles = $("#roleIds").val();
        if(roles != null && roles != 'undefined' && roles != ''){
            roles = roles.split(',');
            for(var i=0; i<roles.length; i++){
                var _role_input = $("#role_id_" + roles[i]);
                _role_input.prop("checked", true);
            }

        }
    },
    loadRoles : function(){
        var _this = this;
        $.ajax({
            url:_this.urlItems.roleListUrl,
            data : {
                pageNo : 1,
                pageSize : 100
            },
            dataType:'json',
            type:'post',
            success:function(data){
                if(data.code != _this.successCode){
                    webDialogUtil.simpleAlert(data.msg);
                }else{
                    var pageResult = data.result;
                    if(pageResult.itemList.length>0){
                        $("#roles_div").html($("#roleTmp").render(pageResult.itemList));
                    }else{
                        $("#roles_div").html('<li class="clearfix"><div class="name">暂无数据</div></li>');
                    }
                    //初始化用户角色ID
                    _this.initRoleList();
                }
            },
            error:function(){
                webDialogUtil.simpleAlert("加载角色异常，请刷新后重试！");
            }
        });
    },
    initMenuList : function(list){
        var _this = this;
        if(!list){
            return;
        }
        $.each(list, function(id,dept){
            var key = dept.id;
            _this.deptList[key] = dept;
            if(dept.subDepts && dept.subDepts.length > 0){
                _this.initMenuList(dept.subDepts);
            }
        });
    },
    loadDepts : function(){
        var _this = this;
        $.ajax({
            url:_this.urlItems.deptListUrl,
            dataType:'json',
            type:'post',
            success:function(data){
                if(data.code != _this.successCode){
                    webDialogUtil.simpleAlert(data.msg);
                }else{
                    var $expandibleTree = $('#treeview-expandible').treeview({
                        data: data.result,
                        levels : 3,
                        nodesName : 'subDepts',
                        text : 'name',
                        nodeIdName : 'id',
                        onNodeCollapsed: function(event, node) {
                            $('#expandible-output').prepend('<p>' + node.text + ' was collapsed</p>');
                        },
                        onNodeExpanded: function (event, node) {
                            $('#expandible-output').prepend('<p>' + node.text + ' was expanded</p>');
                        }
                    });

                    //初始化组织机构数据到menuList
                    _this.initMenuList(data.result);

                    $("#treeview-expandible").on("click",function(e){
                        if(e.target && e.target.nodeName.toLowerCase() == "li") {
                            var _obj = $(e.target);
                            var deptId = _obj.attr("data-id");
                            $("#dept_id").val(deptId);
                            $("#department").val(_this.deptList[deptId].name);
                        }
                    });
                }
            },
            error:function(){
                webDialogUtil.simpleAlert("出现异常,请联系开发人员");
            }
        });
    },
    event : function(){
        this.loadRoles();
        this.loadDepts();
        $("#submitBtn").on("click",function(){
            $('#editForm').bootstrapValidator('validate');
            if($('#editForm').data('bootstrapValidator').isValid()){
                userAdd.add.saveOrUpdate();
            }
        });
        $("#role_button").on("click", function(){
            $("#role_show_div").toggle();
        });
        $("#dept_button").on("click", function(){
            $("#dept_show_div").toggle();
        });
        //运单表单验证
        this.formValidate();
    }
}
$(function(){
    userAdd.add.event();
});
